package com.example.activitydemo;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

/**
 * @author wdl
 */
public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        /**
         * 获取第一个Activity传过来的数据
         */
        Intent intent=getIntent();
        String data=intent.getStringExtra("SecondActivity");
        Toast.makeText(SecondActivity.this,"前一个activity的数据:"+data,Toast.LENGTH_SHORT).show();

        Button mBtnBack = findViewById(R.id.btn_back);
        mBtnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String data1="Hello MainActivity";
                Intent intent1=new Intent(SecondActivity.this,MainActivity.class);
                intent1.putExtra("MainActivity",data1);
                setResult(RESULT_OK,intent1);
                finish();
            }
        });
    }

    /**
     *  防止按返回键导致数据没有传回上一个活动,在这里重写onBackPressed()
     */
    @Override
    public void onBackPressed() {
        String data1="Hello MainActivity";
        Intent intent1=new Intent(SecondActivity.this,MainActivity.class);
        intent1.putExtra("MainActivity",data1);
        setResult(RESULT_OK,intent1);
        finish();
    }
}
